<?php
/**
 +------------------------------------------------------------------------------
 * KitMoney套件资产操作
 +------------------------------------------------------------------------------
 * @package  app
 * @author   alpha <QQ:411083658>
 * @date 2013-9-12
 * @time  下午13:38:07
 +------------------------------------------------------------------------------
 */
class KitMoney {
	protected $line = '';
	protected $isdebug = '';
	/**
	 * SMW01分销用户变动余额
	 * 
	 * @param int $userid
	 *        	用户ID
	 * @param string $subject
	 *        	财务科目 XV TV
	 * @param int $value
	 *        	充值数额 分为单位
	 * @param array $opt=array(
	 *        	'action_userid'=>'操作人',
	 *        	'cip'=>'IP',
	 *        	'bzvu'=>'订单号，授权码，操作原因',
	 *        	'changtype'=>'操作类型 ADMIN_ADD,KIT_ORDER_PAY_XV,KIT_ORDER_BAK,TENPAY_ADD,CVTOXV,TVTOXV,KIT_ORDER_RECE_TV,TVTORMB',
	 * 			'oper' => '-'
	 *        	)
	 * @return 当前余额 或 false
	 *         @date 2013-9-12
	 *         @time 下午3:40:06
	 */
	function recharge($userid = 0, $subject = '', $value = 0, $opt = array(), $isRet = false) {
		if($value>0){
			$value = $value * 100;
		}
		// 用户余额
		$this->line = 'recharge::' . __LINE__;
		if (empty ( $userid )) {
			self::_err ( '用户ID不能为空。' );
		}
		if (empty ( $subject )) {
			self::_err ( '参数错误。' );
		}
		if (empty ( $value ) || $value < 0) {
			self::_err ( '变动数额不能为0' );
		}
		if (empty ( $opt ['changtype'] )) {
			self::_err ( '变动类型必须填写' );
		}
		if (($opt ['changtype'] == 'ADMIN_ADD' || $opt ['changtype'] == 'ORDER_BAK' || $opt ['changtype'] == 'ADMIN_DECR') && empty ( $opt ['action_userid'] )) {
			self::_err ( '充值、退款操作时操作人ID不能为空。' );
		}
		$opt ['action_userid'] = isset ( $opt ['action_userid'] ) ? $opt ['action_userid'] : $userid;
		$assetc = array (
				'platform' => 'SMW01' 
		);
		$assetc ['changtype'] = $opt ['changtype'];
		$assetc ['action_userid'] = $opt ['action_userid'];
		$assetc ['cip'] = $opt ['cip'];
		$assetc ['bzvu'] = $opt ['bzvu'];
		$assetc ['userid'] = $userid;
		$assetc ['subject'] = $subject;
		$assetc ['ctime'] = time ();
		// 获取用户当前的余额
		$money = self::money_info ( $userid, 'SMW01', $subject );
				
		// 写入用户余额
		if (empty ( $money ) && $money !== false) {
			$money = 0;
		}
		
		if(empty($opt ['oper']) || $opt ['oper']=='+'){
			$money = $money + $value;
			$assetc ['value'] = $value;
		}
		if(!empty($opt ['oper']) && $opt ['oper']=='-'){
			if($money < $value){
				if($isRet==false){
					return false;
				}else{
					return -1;
				}
			}else{
				$money = $money - $value;
				$assetc ['value'] = '-'.$value;
			}
		}
		$where = array ();
		$where ['userid'] = $userid;
		$where ['subject'] = $subject;
		$where ['platform'] = 'SMW01';
		$data = $where;
		$usermoney = M ( 'KitAgentMoney' );
		$res = $usermoney->where ( $where )->find ();
		$usermoney->startTrans ();
		$data ['value'] = $money;
		$data ['mtime'] = time ();
		if ($res) {
			$data ['id'] = $res ['id'];
			$return = $usermoney->save ( $data );
		} else {
			$return = $usermoney->add ( $data );
		}
		if (empty ( $return )) {
			self::_err ( '账号操作错误。' );
		}
		$assetc ['nowvalue'] = $money;
		// 写入充值流水
		$assetc_dao = M ( "KitAgentAssets" );
		$assetc_dao->startTrans ();
		$assetc_id = $assetc_dao->add ( $assetc );
		if ($assetc_id) {
			$usermoney->commit ();
			$assetc_dao->commit ();
			return $money;
		} else {
			$usermoney->rollback ();
			$assetc_dao->rollback ();
			return false;
		}
	} // end recharge
	
	/**
	 * 获取用户余额
	 * 
	 * @param int $userid
	 *        	用户ID
	 * @param string $platform
	 *        	平台信息 SMW01
	 * @param string $subject
	 *        	财务科目 XV TV
	 *        	@date 2013-9-12
	 *        	@time 下午5:58:41
	 */
	function money_info($userid = 0, $platform = 'SMW01', $subject = 'all') {
		// 获取用户余额
		$this->line = 'money_info::' . __LINE__;
		$user = M ( "KitAgentMoney" );
		$where = array ();
		if ($platform != 'all') {
			$where ['platform'] = $platform;
		}
		$where ['userid'] = $userid;
		$info = $user->where ( $where )->select ();
		if (empty ( $info )) {
			return false;
		}
		$res = array ();
		foreach ( $info as $v ) {
			//dump($info);
			$res [$v ['platform']] [$v ['subject']] = $v ['value'];
		}
		if ($platform != 'all') {
			if ($subject != 'all') {
				return $res [$platform] [$subject];
			} else {
				return $res [$platform];
			}
		}
		return $res;
	} // end money_info
	/**
	 * 获取用户余额列表
	 * 
	 * @param array     $_arr=array(
	 * 					'userid'=>用户ID,
	 * 					'platform'=>平台信息 SMW01,
	 * 					'subject'=>财务科目 XV TV,
	 * 					)
	 * @return array
	 */
	function money_list($_arr = array(), $limit = '0,20', $order = 'id DESC') {
		// 获取用户余额
		$this->line = 'money_list::' . __LINE__;
		$model = M ( "KitAgentMoney" );
		$where = array ();
		
		if($_arr != 'all'){
			$where = $_arr;
		}
		
		if (strtolower ( $limit ) == 'all') {
			return $model->where($where)->count ();
		}
		$res = $model->where($where)->order ( $order )->limit ( $limit )->select();
		return $res;
	} // end money_list
	/**
	 * 获取所有用户财务流水
	 * 
	 * @param array     $_arr=array(
	 * 					'userid'=>用户ID,
	 * 					'action_userid'=>操作用户ID,
	 * 					'platform'=>平台信息 SMW01,
	 * 					'subject'=>财务科目 XV TV,
	 * 					'changtype'=>资金变动类型 1RECHARGE_XV:充值XV 2CVTOXV:CV转XV 3TVTOXV:TV转XV 4KIT_ORDER_PAY_XV:套件订单付款XV\r\n5KIT_ORDER_RECE_TV:套件订单结算TV 6TVTORMB:TV提现
	 * 					)
	 * @return array
	 */
	function assets_list($_arr = array(), $limit = '0,20', $order = 'id DESC') {
		// 获取用户余额
		$this->line = 'assets_list::' . __LINE__;
		$model = M ( "KitAgentAssets" );
		$where = array ();
		
		if($_arr != 'all'){
			$where = $_arr;
		}
		
		if (strtolower ( $limit ) == 'all') {
			return $model->where($where)->count ();
		}
		$res = $model->where($where)->order ( $order )->limit ( $limit )->select();
		return $res;
	} // end assets_list
	/**
	 * 用户财务流水
	 * 
	 * @param array $userids
	 *        	用户ID数组
	 *        	@date 2013-9-12
	 *        	@time 下午3:30:30
	 */
	function assets($userids = array(), $platform = 'SMW01', $limit = '0,20', $subject = '',$changtype='') {
		// 用户财务流水
		$dao = M ( "KitAgentAssets" );
		$where = array ();
		$where ['platform'] = $platform;
		$ids = array ();
		if (is_array ( $userids )) {
			foreach ( $userids as $v ) {
				$ids [] = $v ['id'];
			}
		} else {
			$ids [] = $userids;
		}
		if($userids != 'all'){
			$where ['userid'] = array (
					'IN',
					implode ( ',', $ids ) 
			);
		}
		
		if ($subject) {
			$where ['subject'] = array (
					'IN',
					$subject 
			);
		}
		if ($changtype) {
			$where ['changtype'] = array (
					'IN',
					$changtype 
			);
		}
		$res = array ();
		if ($limit == 'all') {
			return $dao->where ( $where )->count ();
		}
		$data = $dao->where ( $where )->order ( "id DESC" )->limit ( $limit )->select ();
		if($userids != 'all'){
			$temp=array();
			foreach ($data as $v) {
				$temp[$v['userid']][]=$v;
			}
			if (is_array ( $userids )) {
				$res = $temp;
			} else {
				$res = $temp [$userids];
			}
		}else{
			$res = $data;
		}
		return $res;
	} // end assets
	
	/**
	 * 输出错误信息
	 * @date 2013-5-6
	 * @time 下午5:19:24
	 */
	function _err($arr = array(), $str = "暂无相关信息") {
		// 请求接口类型异常
		if ($this->isdebug == 1) {
			echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
		}
		if (is_array ( $arr ) && ! empty ( $arr )) {
			$res = array (
					"status" => 0,
					"msg" => $str,
					'data' => $arr,
					'line' => $this->line 
			);
		} else {
			$res = array (
					"status" => 0,
					"msg" => $str,
					'data' => $this->debug,
					'line' => $this->line 
			);
		}
		echo self::myjson ( $res );
		if ($this->isdebug == 1) {
			echo '</textarea>';
		}
		die ();
	} // end _err
	
	/**
	 * 请求成功返回
	 * @date 2011-11-15
	 * @time 上午08:10:19
	 */
	private function _suc($arr = array(), $str = "操作成功") {
		// 请求接口类型异常
		$res = array (
				"status" => 1,
				"msg" => $str,
				'data' => $this->debug 
		);
		if (! empty ( $arr )) {
			$res = array_merge ( $res, $arr );
		}
		if ($this->isdebug == 1) {
			echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
		}
		echo self::myjson ( $res );
		if ($this->isdebug == 1) {
			echo '</textarea>';
		}
		die ();
	} // end _suc
	private function myjson($code) {
		$code = json_encode ( $this->urlencodeAry ( $code ) );
		return urldecode ( $code );
		//return $code;
	}
	/******************************
	*订单商品处理
	*******************************/	
	function Statistics($type=array()){
		if(empty($type)){
				return false;
		}
		$finance = M('order_finance');			
		$paypa = M('order_real_pay');
		$total = array();
		//查询订单扩展表里面是否缺货  如果缺货 减去缺货的金额
		foreach ($type as $t_key => $t_value) {
			//dump($t_value);
			$temp_total = 0;
			$temp_finance = 0;
			$orderid = 0;
			foreach ($t_value as $tv_key => $tv_value) {
				//dump($tv_value);
				$orderid = $tv_value['order_id'];
				//dump($tv_value);
				$temp_total += $tv_value['priceall'];
				//查询缺货退款总
				$where['goods_id'] = $tv_value['product_id'];
				$where['order_id'] = $tv_value['order_id'];
				$where['subject'] = 'CV';
				$where['platform'] = 'SMW01';
				$where['action'] = array(array('eq','OOS'),array('eq','REFUND'),'OR'); 
				$where['status'] = '1';
				//$financeinfo = $finance->where($where)->select(); //查看扩展表里面该商品是否缺货；
				//dump($financeinfo);exit;
				$temp_finance += $finance->where($where)->sum('value*number');
				//dump($temp_finance);
				//dump($finance->getLastSql());
				
				/*foreach ($financeinfo as $f_key => $f_value) {
					$temp_finance += $f_value['value'];
				}*/
			}
			$temp_total -= $temp_finance;
			$total[$t_key]['total'] = $temp_total;
			$total[$t_key]['order_id'] = $orderid;
		}
		$ret = 0;
		foreach ($total as $key => $value) {
			$data['order_id'] = $value['order_id']; //订单编号
			$data['mname'] = $key; //商品类型
			$data['value'] = $value['total']; //计算出来的价格
			$data['ctime'] = time();
			$Verification['mname'] = $key;
			$Verification['order_id'] = $value['order_id'];
			$realpayinfo = $paypa->where($Verification)->select(); //防止重复添加
			
			$data['id'] = $realpayinfo[0]['id'];
			$ret = $paypa->add($data,array(),true);
		}
		return $ret;
	}
	/******************************
	*@order_statis 会员订单统计
	*@$ordernum 订单编号  
	*******************************/
	function order_statis($ordernum){
		if(empty($ordernum)){
			return false;
		}
		$order = M('order');
		$where = array();
		$where['sn'] = $ordernum;
		//$where['platform'] = 'SMW01';
		//获取该订单下面的订单商品
		$result = $order->field('g.order_id,g.product_id,g.priceall,g.mname')->join('as o inner join order_goods as g ON o.id = g.order_id')->where($where)->select();
		if(!$result){
			return false;
		}
		$total = 0;
		$arr = array();
		foreach ($result as $key => $value) {
			if($value['mname'] == ''){
				foreach ($value as $k => $v) {
					if($k == 'mname' && $v == ''){
						$value['mname'] = 'sj';
					}
				}
				$arr['sj'][] = $value;
			}else{
				$arr[$value['mname']][] = $value;
			}
			
		}
		//dump($arr);
		$data = $this->Statistics($arr);
		return $data;
	}
	/**
	 * 获取订单实际支付总金额
	 * @param string $orderid 订单ID
	 * @return int 总金额
	 * */
	 function get_order_pay_total($orderid){
	 	$model = M('OrderRealPay');
		$where = array();
		$where['order_id']=$orderid;
		$res = $model->where($where)->sum('value');
		return $res;
	 }
	 /**
	 * 获取订单商品分类实际支付总金额
	 * @param string $orderid 订单ID
	 * @return array()
	 * */
	 function get_order_type_pay_total($orderid){
	 	$model = M('OrderRealPay');
		$where = array();
		$where['order_id']=$orderid;
		$res = $model->field('mname,value')->where($where)->select();
		return $res;
	 }
}//end Money